<?php
/**
 * Eren Framework
 * 
 * UpLoad class
 * 
 * @category System
 * @author Manu Soros Leu
 * @copyright manusoros@gmail.com
 */

class Eren_UpLoad
{
    /**
     * Down Header
     * 
     * @param string $fileName
     * @param strint $charset
     */
    public static function SaveFile($uploadFile, $newForder, $fileName = NULL)
    {
        if(empty($_FILES)){
            throw new Eren_Exception('$_FILES is empty, maybe the file is too big.', -1);
        }else if(isset($_FILES[$uploadFile]['error']) && $_FILES[$uploadFile]['error'] != 0){
            if($_FILES[$uploadFile]['error'] == 1 || $_FILES[$uploadFile]['error'] == 2){
                throw new Eren_Exception('The file is too big.', -1);
            }else if($_FILES[$uploadFile]['error'] == 4){
                throw new Eren_Exception('Please choose a file to upload.', -1);
            }else {
                throw new Eren_Exception('Upload err:' . $_FILES[$uploadFile]['error'] . '.', -1);
            }
        }else{
            $tmpName = $_FILES[$uploadFile]['tmp_name'];
            $name = $_FILES[$uploadFile]['name'];
            if(!Eren_File::isExist($newForder) || !Eren_File::isDir($newForder)){
                throw new Eren_Exception("The forder[{$newForder}] is not exist or is not a forder.", -1);
            }
            if($fileName == NULL){
                $fileName = $name;
            }
            
            $pathinfo = pathinfo($name);
            $ext      = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
            
            if(@rename($tmpName, "{$newForder}/{$fileName}.{$ext}") == false){
                throw new Eren_Exception("Mv file err, maybe you dont have the right.", -1);
            }
        }
        
        return "{$newForder}/{$fileName}.{$ext}";
    }
}